package com.example.book.in.service;

import com.example.book.base.BaseService;
import com.example.book.crawler.dao.CrawlerCatalogDao;
import com.example.book.crawler.entity.CrawlerCatalog;
import com.example.book.in.entity.BookInfo;
import com.example.book.in.dao.BookInfoDao;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author hcj
 * @date 2019-10-27 22:24:17
 */
@Service
public class BookInfoService extends BaseService<BookInfo, BookInfoDao> {

    @Autowired
    private CrawlerCatalogDao crawlerCatalogDao;

    /**
     * 首页完本随机推荐
     *
     * @param limit
     * @return
     */
    public List<BookInfo> findEndBookByRand(Integer limit) {
        return dao.findEndBookByRand(limit);
    }

    /**
     * 物理分页查询
     *
     * @param bookInfo
     * @return
     */
    public PageInfo<BookInfo> findListBySearch(BookInfo bookInfo) {
        PageInfo<BookInfo> pageInfo = PageHelper.startPage(bookInfo.getPageNum(), bookInfo.getPageSize())
                .doSelectPageInfo(() -> dao.findListBySearch(bookInfo));
        return pageInfo;
    }

    /**
     * 设置热门书籍状态
     *
     * @param id
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void setPopularSearches(String id) {
        dao.setPopularSearches(id);
    }

    /**
     * 查询后台设置的热门搜索
     *
     * @return
     */
    public List<BookInfo> selectPopularSearches(Integer limit) {
        return dao.selectPopularSearches(limit);
    }

    public List<BookInfo> findSelect2() {
        return super.findList(new BookInfo());
    }

    /**
     * 根据状态查询未处理的书籍信息
     *
     * @param limit
     * @return
     */
    public List<BookInfo> findListByLimit(Integer limit) {
        return dao.findListByLimit(limit);
    }

    /**
     * 保存到抓取书籍信息位置 更新书籍信息状态
     *
     * @param crawlerCatalog
     * @param info
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void saveCCAndUpdate(CrawlerCatalog crawlerCatalog, BookInfo info) {
        crawlerCatalog.setCreateDate(new Date());
        crawlerCatalog.setUpdateDate(new Date());
        crawlerCatalog.setDelFlag("0");
        crawlerCatalog.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        crawlerCatalogDao.insert(crawlerCatalog);
        dao.update(info);
    }
}